<template>
  <el-container class="main-container">
    <el-container>
      <el-container>
        <el-main>

          <div class="guidance-info">
            <el-row class="toolbar">
              <el-row>
                <el-col :span="12" class="guidance-text" style="text-align: left;">
                <p>请搜索来筛选停车场引导信息：</p>
              </el-col>
              <el-col :span="12" class="action-area">
                <el-button type="primary" icon="el-icon-map-location" @click="navigateTo('DeviceInfo')">
                  To Device Information
                </el-button>

                <el-button type="success" icon="el-icon-plus" @click="openAddDialog">
                  Add Parking Guidance
                </el-button>
              </el-col>
              </el-row>

              <el-col :span="24" class="search-area">
                <el-select v-model="searchForm.carParkID" filterable remote reserve-keyword
                  placeholder="停车场ID或名称查找" :remote-method="fetchCarParkOptions" :loading="isLoadingCarParks"
                  clearable class="search-select">
                  <el-option v-for="item in carParkOptions" :key="item.carParkID" :label="item.name"
                    :value="item.carParkID" />
                </el-select>

                <el-input v-model="searchForm.availableSpaces" placeholder="Search by Available Spaces"
                  class="search-input" clearable>
                </el-input>
                <el-input v-model="searchForm.displayLocation" placeholder="Search by Display Location"
                  class="search-input" clearable>
                </el-input>
                <el-button type="primary" icon="el-icon-search" @click="filterGuidances">Search</el-button>
              </el-col>
            </el-row>


            <!-- Parking Guidance Table -->
            <el-table :data="currentGuidances" stripe border :row-class-name="tableRowClassName">
              <el-table-column label="No." width="60" type="index" :index="calculateIndex" />
              <el-table-column prop="guidanceID" label="Guidance ID" width="80" />
              <el-table-column prop="carParkID" label="Car Park ID" width="80" />
              <el-table-column prop="availableSpaces" label="Available Spaces" width="200" />
              <el-table-column prop="updateTime" label="Update Time" width="300" />
              <el-table-column prop="displayLocation" label="Display Location" />
              <el-table-column label="Actions" width="180">
                <template slot-scope="scope">
                  <el-button size="small" type="text" @click="openEditDialog(scope.row)">Edit</el-button>
                  <el-button size="small" type="text" @click="deleteGuidance(scope.row.guidanceID)">Delete</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- Pagination -->
            <el-pagination :current-page="currentPage" :page-size="pageSize" :total="totalGuidances"
              @current-change="handlePageChange">
            </el-pagination>

            <!-- Add/Edit Dialog -->
            <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
              <el-form :model="guidanceForm" label-width="120px">
                <!-- <el-form-item label="Car Park ID">
                  <el-input v-model="guidanceForm.carParkID"></el-input>
                </el-form-item> -->
                <el-form-item label="Car Park ID">
                  <el-select v-model="guidanceForm.carParkID" filterable remote reserve-keyword
                    placeholder="Search and select a car park" :remote-method="fetchCarParks"
                    :loading="isLoadingCarParks" style="width: 100%;">
                    <el-option v-for="item in carParkOptions" :key="item.carParkID" :label="item.name"
                      :value="item.carParkID" />
                  </el-select>
                </el-form-item>
                <el-form-item label="Available Spaces">
                  <el-input v-model="guidanceForm.availableSpaces"></el-input>
                </el-form-item>
                <el-form-item label="Display Location">
                  <el-input v-model="guidanceForm.displayLocation"></el-input>
                </el-form-item>
                <el-form-item label="Update Time">
                  <el-input v-model="guidanceForm.updateTime" disabled></el-input> <!-- Disabled for manual input -->
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">Cancel</el-button>
                <el-button type="primary" @click="saveGuidance">Save</el-button>
              </div>
            </el-dialog>
          </div>



          <!-- Information Cards -->
          <el-row class="info-cards" :gutter="20">
            <el-col :span="8">
              <el-card class="box-card">
                <div slot="header" class="clearfix">
                  <span>智慧引导系统信息</span>
                </div>
                <div>
                  <p>系统名称：智慧停车场引导系统</p>
                  <p>系统版本：V1.0</p>
                  <p>系统编号：GUIDE-2024</p>
                  <p>部署日期：2024-03-15</p>
                  <p>更新周期：每月更新</p>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="box-card">
                <div slot="header" class="clearfix">
                  <span>引导流程说明</span>
                </div>
                <div>
                  <p>1. 车辆进入时，系统自动检测并分配空闲车位。</p>
                  <p>2. 通过LED显示屏和地面指示灯引导司机至指定车位。</p>
                  <p>3. 司机根据系统提示完成停车操作。</p>
                  <p>4. 系统记录停车时间和车位使用情况。</p>
                  <p>5. 离场时，系统自动计算停车费用并提供支付指引。</p>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="box-card">
                <div slot="header" class="clearfix">
                  <span>系统维护与优化</span>
                </div>
                <div>
                  <p>1. 定期检查传感器和摄像头，确保引导准确性。</p>
                  <p>2. 更新软件算法，提高车位分配效率。</p>
                  <p>3. 维护LED显示屏和指示灯，确保清晰可见。</p>
                  <p>4. 检查网络连接，确保系统数据同步。</p>
                  <p>5. 收集用户反馈，持续优化用户体验。</p>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-main>
      </el-container>
    </el-container>
  </el-container>
</template>

<script>
import { getAllParkingGuidances, addParkingGuidance, updateParkingGuidance, deleteParkingGuidance, searchCarParks } from '@/api/parkingGuidanceInfo';
export default {
  name: 'ParkingGuidanceInfo',
  data() {
    return {
      guidances: [],
      currentGuidances: [],
      totalGuidances: 0,
      currentPage: 1,
      pageSize: 5,
      dialogVisible: false,
      dialogTitle: '',
      searchForm: {
        carParkID: '',
        availableSpaces: '',
        displayLocation: '',
      },
      guidanceForm: {
        guidanceID: null,
        carParkID: '',
        availableSpaces: '',
        displayLocation: '',
        updateTime: new Date().toISOString() // Set the current time initially
      },
      carParkOptions: [], // 储存搜索结果
      isLoadingCarParks: false, // 控制搜索加载状态

    };
  },
  computed: {
    filteredGuidances() {
      if (!Array.isArray(this.guidances)) {
        return [];
      }
      return this.guidances.filter((guidance) => {
        return (
          (!this.searchForm.carParkID || guidance.carParkID.toString().includes(this.searchForm.carParkID.toString())) &&
          (!this.searchForm.availableSpaces || guidance.availableSpaces.toString().includes(this.searchForm.availableSpaces.toString())) &&
          (!this.searchForm.displayLocation || guidance.displayLocation.includes(this.searchForm.displayLocation))
        );
      });
    }
  },
  methods: {

    // Navigate to another route
    navigateTo(routeName) {
      this.$router.push({ name: routeName }).catch(err => {
        if (err.name != 'NavigationDuplicated') {
          throw err;
        }
      }); // 跳转到对应路由
    },
    // Fetch all parking guidance records
    fetchParkingGuidances() {
      getAllParkingGuidances().then((response) => {
        this.guidances = response; // Store all parking guidance records
        this.totalGuidances = response.length; // Set total guidances
        this.updateCurrentGuidances(); // Update the current page data
      });
    },
    // Update the data displayed on the current page
    updateCurrentGuidances() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.currentGuidances = this.filteredGuidances.slice(start, end); // Get current page data
    },
    // Handle page change
    handlePageChange(page) {
      this.currentPage = page;
      this.updateCurrentGuidances(); // Update the data for the current page
    },
    openAddDialog() {
      this.dialogTitle = 'Add Parking Guidance';
      this.guidanceForm = { guidanceID: null, carParkID: '', availableSpaces: '', displayLocation: '', updateTime: new Date().toISOString() };
      console.log(this.guidanceForm);
      this.dialogVisible = true;
    },
    openEditDialog(guidance) {
      this.dialogTitle = 'Edit Parking Guidance';
      this.guidanceForm = { ...guidance }; // Populate the form with the selected parking guidance data
      this.dialogVisible = true;
    },
    saveGuidance() {
      const apiCall = this.guidanceForm.guidanceID ? updateParkingGuidance : addParkingGuidance;
      console.log(apiCall)
      apiCall(this.guidanceForm).then(() => {
        this.fetchParkingGuidances(); // Reload the guidance list after save
        this.dialogVisible = false;
      });
    },
    deleteGuidance(guidanceID) {
      this.$confirm('Are you sure to delete this parking guidance?', 'Warning', {
        confirmButtonText: 'Yes',
        cancelButtonText: 'No',
        type: 'warning'
      }).then(() => {
        deleteParkingGuidance(guidanceID).then(() => {
          this.fetchParkingGuidances(); // Reload the guidance list after deletion
        });
      });
    },
    tableRowClassName(row, index) {
      return index % 2 === 0 ? 'even-row' : 'odd-row'; // 示例：交替的行样式
    },
    filterGuidances() {
      this.currentPage = 1;
      this.updateCurrentGuidances();
    },
    calculateIndex(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },


    // 获取停车场数据 addDialoog
    fetchCarParks(query) {
      if (query.trim() === '') {
        this.carParkOptions = [];
        return;
      }
      this.isLoadingCarParks = true;
      searchCarParks(query)
        .then((response) => {
          this.carParkOptions = response || []; // 接收停车场搜索结果
        })
        .finally(() => {
          this.isLoadingCarParks = false;
        });
    },
    // 获取停车场数据searchDialog
    fetchCarParkOptions(query) {
      if (!query.trim()) {
        this.carParkOptions = [];
        return;
      }
      this.isLoadingCarParks = true;
      searchCarParks(query)
        .then((response) => {
          this.carParkOptions = response || [];
        })
        .finally(() => {
          this.isLoadingCarParks = false;
        });
    },


  },
  mounted() {
    this.fetchParkingGuidances(); // Fetch the guidance data when the component is mounted
  }
};
</script>

<style>
.main-container {
  margin-left: 200px;
  margin-top: 100px;
}

/* .guidance-info {
  padding: 20px;
} */

.toolbar {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.search-area {
  display: flex;
  align-items: center;
  gap: 10px;
  /* 增加组件间的间距 */
}

.search-input {
  width: 200px;
  /* 输入框宽度 */
}

.search-select {
  width: 150px;
  /* 下拉框宽度 */
}

.action-area .el-button {
  margin-left: 10px;
  /* 按钮间距 */
}

/* 菜单 */
.search-select {
  width: 200px;
}

.info-cards {
  margin-top: 20px;
}

.el-card__header {
  padding: 15px;
  background-color: #f9f9f9;
  border-bottom: 1px solid #ebeef5;
}

.el-card__body {
  padding: 15px;
}

.box-card {
  margin-bottom: 20px;
  transition: transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out;
  cursor: pointer;
}

.box-card:hover {
  transform: scale(1.05);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
}
</style>